<script setup>
import {ref, onMounted, defineEmits} from "vue";
import {loadStripe} from "@stripe/stripe-js";
import {Elements, CardElement, useStripe, useElements} from '@stripe/react-stripe-js';
import SrMessages from "./SrMessages.vue";
import {getStripeSessionId} from "@/api/order.ts";
import {Local, Session} from "@/utils/storage.ts";
import {useCurrencyStore} from '@/store/currency.ts'
import {getSetting} from "@/api/help.ts";

const props = defineProps({
  amount: {
    type: Number,
    required: true
  },
  orderId: {
    type: Number || String,
    required: true
  },
  addressDetail: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['payment-success']);
const useCurrency = useCurrencyStore()
const orderParams = ref({
  currency: '',
  amount: props.amount,
  order_id: props.orderId,
})

// 定义一个响应式变量，用于表示加载状态
const isLoading = ref(false);
// 定义一个响应式数组，用于存储消息
const messages = ref([]);

// 声明Stripe和elements变量
let stripe;
let elements;
let clientSecret;
const siteKey = ref('')
//获取网站密钥
const getSiteKey = async () => {
  const res = await getSetting();
  if (res.code === 200) {
    siteKey.value = res.result.stripe_pay_key;
    Local.set('settingConfig', res.result)
  }
}
// 组件挂载时执行的异步函数
onMounted(async () => {
  orderParams.value.currency = useCurrency.currentCurrency.currency_code ? useCurrency.currentCurrency.currency_code : 'USD'
  // 从后端获取publishableKey
  // const { publishableKey } = await fetch("/api/config").then((res) => res.json());
  // const publishableKey = 'pk_test_51QqnilLS6KVPfMFkSFbV0ZkolflCi29HEV6wdbSP5MBVaYRyEdMeD9WpbDpSnl828zDZ0WiFTHctSQiEvh15VJMR00RYYOWkML'
  if (!Local.get('settingConfig')) {
    await getSiteKey();
  } else {
    siteKey.value = Local.get('settingConfig').stripe_pay_key
  }

  const publishableKey = siteKey.value
  // 使用publishableKey初始化Stripe
  stripe = await loadStripe(publishableKey);
  console.log('publishableKey', stripe, publishableKey)
  // 从后端获取clientSecret和可能的错误信息
  const res = await getStripeSessionId(orderParams.value)
  if (res.code == 1) {
    clientSecret = res.data.clientSecret;
    Session.set('clientSecret', res.data.clientSecret)
    // 将成功获取clientSecret的信息推入消息数组
    messages.value.push(`Client secret returned.`);
    // 使用clientSecret初始化Stripe Elements
    elements = stripe.elements({clientSecret});
    // 创建支付元素并挂载到指定的DOM节点
    const paymentElement = elements.create('payment');
    paymentElement.mount("#payment-element");
    // 创建链接认证元素并挂载到指定的DOM节点
    const linkAuthenticationElement = elements.create("linkAuthentication");
    linkAuthenticationElement.mount("#link-authentication-element");
    // 设置加载状态为false
    isLoading.value = false;
  } else {
    messages.value.push(res.message);
  }

  // 如果有错误信息，将其推入消息数组
  // if (backendError) {
  //   messages.value.push(backendError.message);
  // }

});

// 定义处理表单提交的异步函数
const handleSubmit = async () => {
  // 如果当前正在加载，则直接返回
  if (isLoading.value) {
    return;
  }

  // 设置加载状态为true
  isLoading.value = true;

  // 准备账单详情，优先使用地址详情
  const billingDetails = {
    name: props.addressDetail.name || 'Unknown',
    email: '', // 地址详情中可能没有email
    address: {
      line1: props.addressDetail.address || '',
      city: props.addressDetail.city || '',
      postal_code: props.addressDetail.zip_code || '',
      country: props.addressDetail.country_code || 'US',
      state: props.addressDetail.province || ''
    }
  }

  // 调用Stripe的confirmPayment方法进行支付确认
  const {error, paymentIntent} = await stripe.confirmPayment({
    elements,
    confirmParams: {
      payment_method_data: {
        billing_details: billingDetails
      },
      // 设置支付成功后的重定向URL
      return_url: `${window.location.origin}/user/checkout`,
      // return_url: `${window.location.origin}/order/paySuccess`
    },
    redirect: 'if_required'
  });
  if (paymentIntent && paymentIntent.status == 'succeeded') {
    emit('payment-success');
  }
  console.log('paymentIntent', paymentIntent)
  // 根据错误类型推送不同的错误信息到消息数组
  if (error.type === "card_error" || error.type === "validation_error") {
    messages.value.push(error.message);
  } else {
    messages.value.push("An unexpected error occured.");
  }

  // 设置加载状态为false
  isLoading.value = false;
}

const prevStep = () => {
  emit('prev-step')
}
</script>
<template>
  <main>
    <h1>Payment</h1>

    <p>
      Enable more payment method types
      <a
          href="https://dashboard.stripe.com/settings/payment_methods"
          target="_blank"
      >in your dashboard</a>.
    </p>

    <form
        id="payment-form"
        @submit.prevent="handleSubmit"
    >
      <!-- 链接认证元素的挂载点 -->
      <div id="link-authentication-element"/>
      <!-- 支付元素的挂载点 -->
      <div id="payment-element"/>
      <!-- 提交按钮，禁用状态由isLoading控制 -->
      <!--      <div class="btn-box">-->
      <!--        <SiteButton-->
      <!--            id="submit"-->
      <!--            :disabled="isLoading"-->
      <!--            text="Pay now"-->
      <!--            :immediate="false"-->
      <!--            :btnDefault="true"-->
      <!--            class="checkout-btn">-->
      <!--        </SiteButton>-->
      <!--      </div>-->
      <button
          class="btn-box"
          id="submit"
          :disabled="isLoading"
      >
        Pay now
      </button>
      <a-button
          class="btn-box"
          @click="prevStep"
      >
        Previous
      </a-button>

      <!-- 显示消息的组件 -->
      <!--      <sr-messages :messages="messages"/>-->
    </form>
  </main>
</template>

<style scoped lang="scss">
.btn-box {
  margin-right: 15px;
  margin-top: 20px;
  width: 140px;
  height: 50px;
  background-color: #0c0c0c;
  color: #FFFFFF;
  padding: 10px;
  font-size: 14px;
  border-radius: 8px;
  border: none;
}
</style>
